package com.sit.controller;

import com.sit.service.CaptchaService;
import com.sit.utils.CaptchaUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    @RequestMapping("/CaptchaHtml")
    public String CaptchaHtml() {
        return "CaptchaTest";
    }

    @RequestMapping("/captcha")
    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        captchaService.storeCaptchaInSession(session, 4);
        byte[] captchaImage = captchaService.generateCaptchaImage(150, 40, 4);

        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        // 直接将字节数组写入响应输出流
        response.getOutputStream().write(captchaImage);
        response.getOutputStream().flush();
    }


    @RequestMapping("/verify")
    @ResponseBody
    public static String verifyCaptcha(HttpServletRequest request, String userCaptcha) throws Exception {
        HttpSession session = request.getSession();
        String AesCaptcha = (String) session.getAttribute("AesCaptcha");
        String encryptedCaptcha = CaptchaUtil.decrypt(AesCaptcha);
        if (AesCaptcha != null && encryptedCaptcha.equalsIgnoreCase(userCaptcha)) {
            return "success";
        } else {
            return "failure";
        }
    }
}